<?php


namespace App\Http\service;
use App\Exceptions\ApiException;
use App\Models\Sys;
use EasyWeChat\Factory;
use Illuminate\Support\Facades\Log;


class PayService
{
    public $app;
    public function __construct()
    {
        $this->sysModel=new Sys();
        $config = [
            // 必要配置
            'app_id'             => Sys::getValue("wx_appid"),
            'mch_id'             =>Sys::getValue("mch_id"),
            'key'                => Sys::getValue("mch_key"),   // API v2 密钥 (注意: 是v2密钥 是v2密钥 是v2密钥)

            'notify_url'         => Sys::getValue("api_url")."user/order/pay_notify",     // 你也可以在下单时单独设置来想覆盖它
        ];

        $app = Factory::payment($config);
        $this->app=$app;
    }

    public function get_app()
    {
        return $this->app;
    }

    public function wx_pay($data)
    {
        $res=$this->app->order->unify([
            'body' => '订单支付',
            'out_trade_no' => $data["order_num"],
            'total_fee' => $data["price"]*100,
            'trade_type' => 'JSAPI', // 请对应换成你的支付方式对应的值类型
            'openid' => $data["openid"],
        ]);
        Log::error($data);
        if($res['return_code']=='SUCCESS'&&$res['result_code'] == 'SUCCESS'){
            $prepayId = $res['prepay_id'];
            $json =$this->app->jssdk->sdkConfig($prepayId);
            return $json;

        }else{
            Log::error($res);
            throw new ApiException("调取支付失败");
        }

    }
}
